<template>
  <view>

    <!-- 搜索框 -->
    <view class="tn-flex-center-between">
      <wd-search custom-class="tn-flex-1" hide-cancel placeholder="输入门店查找">
        <wd-drop-menu #prefix>
          <wd-drop-menu-item title="遵义" disabled/>
        </wd-drop-menu>
      </wd-search>
      <view class="tn-p-xs tn-pr-sm">
        <wd-icon name="location"/>
        <text>收起地图</text>
      </view>
    </view>

    <!-- 地图组件 -->
    <map class="tn-w-full" style="height: 160px"></map>

    <!-- 店铺列表 -->
    <view class="tn-p-sm tn-radius">
      <wd-tabs v-model="tab" slidable="always">
        <wd-tab title="附近店铺"></wd-tab>
        <wd-tab title="收藏&常去"></wd-tab>
      </wd-tabs>

      <view v-if="locationAuth">
        <view class="tn-flex-center-between tn-pt tn-pl">
          <wd-img custom-class="tn-shadow" height="100px" width="100px"/>
          <view class="tn-flex-1 tn-pl">

            <view class="tn-text-bold tn-text-lg tn-text-ellipsis-1" style="height: 21px">汇川区聚来笋香土鸡餐馆
            </view>
            <view class="tn-text-sm tn-pt-xs tn-gray-dark_text">23km | address</view>
            <view class="tn-text-sm tn-pt-sm">营业时间：9：00 - 22：00</view>
          </view>

        </view>
      </view>

      <view v-else class="tn-p-xl">
        <wd-gap height="50px"/>
        <wd-button icon="location" open-type="openSetting" block>获取定位</wd-button>
      </view>

    </view>
  </view>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import type {storeAddress} from "@/types/store";
import {onLoad} from "@dcloudio/uni-app";
import {StoreAddressApi} from "@/api/store";
import {get} from "lodash-es";

const locationAuth = ref<boolean>(false)
const stores = ref<storeAddress[]>()

const params = ref<StoreAddressPageReq>({
  pageNo: 1,
  pageSize: 10,
  latitude: "0",
  longitude: "0"
})

onLoad(async () => {
  await authLocation()
})

/**
 * 校验定位权限
 */
async function authLocation() {
  // 查询授权有没有打开定位权限，否则打开设置
  let {authSetting} = await uni.getSetting()
  // 没有申请过定位权限，申请一下定位权限
  if (authSetting['scope.userLocation'] == undefined)
    uni.authorize({scope: 'scope.userLocation'})
        .then(() => getLocation())
        .catch(() => uni.showToast({title: "授权失败", icon: "none"}))
  else if (!authSetting['scope.userLocation']) await uni.openSetting()
  else await getLocation()
}

/**
 * 获取定位信息
 */
async function getLocation() {
  let {latitude, longitude} = await uni.getLocation({type: 'wgs84'})
  console.log("获取到定位信息", latitude, longitude)
  if (latitude == undefined)
    await uni.showToast({title: "定位失败", icon: "none"})
  locationAuth.value = true
  params.value.latitude = latitude.toString()
  params.value.longitude = longitude.toString()
  stores.value = await StoreAddressApi.page(params.value)
}

</script>
